package cn.lpq.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.lpq.magnetsearch.MagentInfo;
import cn.lpq.magnetsearch.MagentSearchFactory;
import cn.lpq.manage.HeikeyunManage;

/**
 * Controller
 * 
 * @author 依旧smile
 *
 */
@RestController
public class HeikeyunController {

	@Resource
	private HeikeyunManage heikeyunManage;

	@RequestMapping("/")
	ModelAndView home() {
		ModelAndView modelAndView = new ModelAndView("index.html");
		return modelAndView;
	}

	@RequestMapping("/parseMagnet")
	public @ResponseBody List<Map<String, String>> parseMagnet(@RequestParam("magnet") String magnet) {
		return heikeyunManage.parseMagnet(magnet, null);
	}

	@RequestMapping("/download")
	public @ResponseBody Map<String, String> download(@RequestParam("data") String data,
			@RequestParam("s1") String s1) {
		String downUrl = heikeyunManage.download(data, s1);
		Map<String, String> map = new HashMap<String, String>();
		map.put("downUrl", downUrl);
		return map;
	}

	@RequestMapping("/uploadTorrent")
	public @ResponseBody List<Map<String, String>> uploadTorrent(MultipartFile file) throws IOException {
		File tempFile = File.createTempFile(System.getProperty("java.io.tmpdir"), ".torrent");
		file.transferTo(tempFile);
		return heikeyunManage.parseMagnet("", tempFile);
	}

	@RequestMapping("/magnetSearch")
	public @ResponseBody List<MagentInfo> magnetSearch(@RequestParam("circuit") int circuit,
			@RequestParam("keyword") String keyword) {
		return MagentSearchFactory.build(circuit).magentSearch(keyword);
	}

}
